import { useDispatch } from 'react-redux'
import { delTodo, updataTodo, updateText } from '../store/actions/todos'
import { useState, useEffect, useRef } from 'react'
export default function TodoItem({ item }) {
  const dispatch = useDispatch()
  const [current, setCurrent] = useState({ id: '', name: '' })
  // 删除
  const del = (id) => {
    dispatch(delTodo(id))
  }
  const inpRef = useRef(null)
  useEffect(() => {
    if (current.id) {
      inpRef.current.focus()
    }
  }, [current])
  const onKeyUp = (e) => {
    if (e.keyCode === 27) {
      return setCurrent({ id: '', name: '' })
    }
    if (e.keyCode === 13) {
      dispatch(updateText(current))
      setCurrent({ id: '', name: '' })
    }
  }
  return (
    <li
      className={[
        item.done ? 'completed' : '',
        current.id ? 'editing' : '',
      ].join(' ')}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={item.done}
          onChange={(e) => dispatch(updataTodo(item.id, e.target.checked))}
        />
        <label
          onDoubleClick={() => setCurrent({ id: item.id, name: item.name })}
        >
          {item.name}
        </label>
        <button className="destroy" onClick={() => del(item.id)} />
      </div>
      <input
        className="edit"
        ref={inpRef}
        value={current.name}
        onChange={(e) => setCurrent({ ...current, name: e.target.value })}
        onBlur={() => setCurrent({ id: '', name: '' })}
        onKeyUp={onKeyUp}
      />
    </li>
  )
}
